import React from 'react';
import {
  Card,
  Button,
  Row,
  Col,
  Icon,
  Tabs,
  Table,
  Radio,
  DatePicker,
  Tooltip,
  Menu,
  Dropdown,
  Input,
  Divider,
  message,
  Upload,
  Modal,
  List,
  Switch,
  notification,
  Avatar,
  Popconfirm
} from 'antd';

import { StyleSheet, css } from 'aphrodite';

import { swap } from 'react-magic';
import styles from './AddTemplateNews.less';
import moment from 'moment/moment';
import { getValueWithLocalStorage } from '@/utils/authority';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const { MonthPicker, RangePicker } = DatePicker;
const { Meta } = Card;

import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

const styles_animation = StyleSheet.create({
  magic: {
    animationName: swap,
    animationDuration: '1s',
  },
});

import { connect } from 'dva';

const namespace = 'news';

const userInfo = getValueWithLocalStorage('userinfo');

import router from 'umi/router';

const mapStateToProps = state => {
  const ret = state[namespace].ret;
  const isLoading = state[namespace].isLoading;
  const categorys = state[namespace].categoryList;

  return {
    ret,
    isLoading,
    categorys
  };
};

const mapDispatchToProps = dispatch => {
  return {
    addNewsDetail: (para, _owner, callback) => {
      const action = {
        type: `${namespace}/addNewsDetail`,
        payload: {
          ...para,
          addCallback: callback,
          owner: _owner,
        },
      };
      dispatch(action);
    },

    editNewsDetail: (para, _owner, callback) => {
      const action = {
        type: `${namespace}/editNewsDetail`,
        payload: {
          ...para,
          onEditCallback: callback,
          owner: _owner,
        },
      };
      dispatch(action);
    },

    getNewsCategorys: () => {
      const action = {
        type: `${namespace}/getNewsCategorys`,
        payload: {
          key: '',
          page: '0',
          pagesize: '100',
        },
      };
      dispatch(action);
    },

    getNewsDetail: (id,callback) => {
      const action = {
        type: `${namespace}/getNewsDetail`,
        payload: {
          id: id,
          callback:callback
        },
      };
      dispatch(action);
    },
  };
};
@connect(
  mapStateToProps,
  mapDispatchToProps
)
export default class AddTemplateNews extends React.Component {
  constructor(props) {
    super(props);
    var isNew =  this.props.location.query.id == undefined
    this.state = {
      _id: isNew ? '' : this.props.location.query.id,
      title: '',
      titledesc:'',
      category:{},
      medias:[],
      isonline:'0',
      isNew: isNew,
      value:'',
      category_index:0
    };
  }

  /*****************************model's callback********************************/

  addCallback = res => {
    if (res.code == 0) {
      message.error(res.msg);
    } else {
      message.success(res.msg);
      router.push('/news/list');
    }
  };

  /**
   * 编辑保存的回调
   * @param res
   */
  onEditCallback = res => {
    if (res.code == 0) {
      message.error(res.msg);
    } else {
      message.success(res.msg);
      router.push('/news/list');
    }
  };

  componentDidMount = () => {
    this.props.getNewsCategorys()
    var that = this

    if(!this.state.isNew){
      that.props.getNewsDetail(that.state._id,res=>{
        var arr = []
        if(res.picurl != undefined){
          arr.push(res.picurl)
        }
        that.setState({
          title: res.title,
          titledesc: res.desc,
          category: res.category,
          medias:arr,
          isonline: res.isonline,
          value:res.html,
        },()=>{
          that.props.categorys.map((item,index)=>{
            if(item.name == that.state.category.name){
              that.setState({category_index:index})
              return
            }
          })
        })
      })
    }

  };

  render() {
    var that = this;

    const modules = {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'], // toggled buttons
        ['blockquote', 'code-block'],

        [{ header: 1 }, { header: 2 }], // custom button values
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
        [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
        [{ direction: 'rtl' }], // text direction

        [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
        [{ header: [1, 2, 3, 4, 5, 6, false] }],

        [{ color: [] }, { background: [] }], // dropdown with defaults from theme
        [{ font: [] }],
        [{ align: [] }],
        ['link', 'image', 'video'],
        ['clean'],
      ],
    };

    const topContent = (
      <Row className={styles.row} gutter={10}>
        <Col span={3}>
          <span className={styles.tipLab}>选择活动类型</span>
        </Col>
        <Col span={10}>
          <RadioGroup
            value={that.state.category_index}
            className={styles.typeBg}
            onChange={e => {
              that.setState(
                {
                  category:that.props.categorys[e.target.value],
                  category_index:e.target.value
              });
            }}
          >
            {
              that.props.categorys.map((item,index)=>{
                return <RadioButton value={index}>{item.name}</RadioButton>
              })
            }
          </RadioGroup>
        </Col>
      </Row>
    );


    const NUM_TITLE = 20;
    const NUM_TITLEDESC = 30;
    const NUM_CONTENT = 140;
    const NUM_PIC = 1;
    const userInfo = getValueWithLocalStorage('userinfo');
    const { previewVisible, previewImage } = this.state;

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const dateFormat = 'YYYY-MM-DD';

    return (
      <Card title={that.state.isNew ? '发布新闻' : '编辑新闻'} bordered={false}>
        {topContent}

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>新闻标题</span>
          </Col>
          <Col span={10}>
            <Input
              defaultValue={that.state.title}
              onChange={e => {
                if (e.target.value.length > NUM_TITLE) {
                  message.warning('超出字数限制');
                  return;
                }
                that.setState({ title: e.target.value });
              }}
            />
          </Col>
          <Col span={3}>
            <span>
              {NUM_TITLE - that.state.title.length}/{NUM_TITLE}
            </span>
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>新闻标题描述</span>
          </Col>
          <Col span={18}>
            <TextArea
              row={2}
              value={that.state.titledesc}
              onChange={e => {
                if (e.target.value.length > NUM_TITLEDESC) {
                  message.warning('超出字数限制');
                  return;
                }
                that.setState({ titledesc: e.target.value });
              }}
            />
          </Col>
          <Col span={3}>
            <span>
              {NUM_TITLEDESC - that.state.titledesc.length}/{NUM_TITLEDESC}
            </span>
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>新闻内容</span>
          </Col>
          <Col span={20}>
            <ReactQuill
              theme="snow"
              modules={modules}
              value={this.state.value}
              onChange={(value)=>{
                  that.setState({value:value})
              }}
            />
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>新闻图片</span>
          </Col>
          <Col span={18}>
            {
               that.state.isNew?
                 <Upload
                   listType={'picture'}
                   action={'/web/file/picUploadWeb?'}
                   defaultFileList={that.state.medias}
                   onRemove={(file)=>{
                     that.setState({medias:[]})
                   }}
                   onChange={(file, fileList)=>{
                     if (file.file.status == 'done') {
                       var arr = []
                       var item = file.file
                       item.url = '/web/'+item.response.ret.url
                       item.originurl = item.response.ret.url
                       arr.push({
                         name:item.name,
                         url:item.url,
                         originurl:item.originurl,
                         uid:item.uid,
                         status:item.status,
                         type:item.type,
                         id:item._id
                       })
                       that.setState({medias:arr})
                     }
                   }}
                 >
                   <Button>
                     <Icon type="upload" /> 上传素材(仅限图片和视频)
                   </Button>
                 </Upload>
                 :
                <Upload
                  listType={'picture'}
                  action={'/web/file/picUploadWeb?'}
                  fileList={that.state.medias}
                  onRemove={(file)=>{
                    that.setState({medias:[]})
                  }}
                  onChange={(file, fileList)=>{
                    if (file.file.status == 'done') {
                      var arr = []
                      var item = file.file
                      item.url = '/web/'+item.response.ret.url
                      item.originurl = item.response.ret.url
                      arr.push({
                        name:item.name,
                        url:item.url,
                        originurl:item.originurl,
                        uid:item.uid,
                        status:item.status,
                        type:item.type,
                        id:item._id
                      })
                      that.setState({medias:arr})
                    }
                  }}
                >
                  <Button>
                    <Icon type="upload" /> 上传素材(仅限图片和视频)
                  </Button>
                </Upload>

            }

            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </Col>
        </Row>


        {that.state.isNew ? (
          <Row className={styles.row} gutter={10}>
            <Col span={3}>
              <span className={styles.tipLab}>是否立即上线</span>
            </Col>
            <Col span={16}>
              <Switch
                className={styles.offBtnStyle}
                checkedChildren="上线"
                unCheckedChildren="下线"
                defaultChecked
                onChange={checked => {
                  that.setState({ isonline: checked });
                }}
              />
            </Col>
          </Row>
        ) : null}

        <Row className={styles.row} gutter={48}>
          <Col offset={3} span={18}>
            <Button
              type="primary"
              block
              onClick={() => {
                if(that.state.category.name == undefined){
                  message.error('分类不能为空!')
                  return
                }
                if(that.state.title.length == 0){
                  message.error('标题不能为空!')
                  return
                }
                if(that.state.titledesc.length == 0){
                  message.error('描述不能为空!')
                  return
                }

                if (that.state.isNew) {
                  that.props.addNewsDetail(that.state, userInfo.tel, that.addCallback);
                } else {
                  that.props.editNewsDetail(
                    that.state,
                    userInfo.tel,
                    that.onEditCallback
                  );
                }
              }}
            >
              {that.state.isNew ? '发布' : '保存编辑'}
            </Button>
          </Col>
        </Row>
      </Card>
    );
  }
}
